package cn.neusoft.yp.controller;

import cn.neusoft.yp.pojo.*;
import cn.neusoft.yp.service.OrderService;
import cn.neusoft.yp.tool.PaymentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * Created by gaosheng on 2017/4/27.
 */
@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;

    @RequestMapping("addOrder")
    public String addOrder(){
        return "addOrder" ;
    }

    @RequestMapping("saveOrder")
    public String saveOrder(String receiverinfo,HttpSession session) {
        Object obj = session.getAttribute("user_session");
        Order order = new Order();
        User user = (User) obj;
        order.setUser_id(user.getId());
        order.setId(UUID.randomUUID().toString());
        order.setPaystate(0);
        order.setOrdertime(new Date());
        order.setReceiverinfo(receiverinfo);
        double money = 0;
        List<OrderItem> list = new ArrayList<OrderItem>();
        Map<Product, Integer> cart = (Map<Product, Integer>) session.
                getAttribute("cart");
        for (Map.Entry<Product, Integer> entry : cart.entrySet()) {
            money += entry.getValue() * entry.getKey().getPrice();
            OrderItem oi = new OrderItem();
            oi.setOrder_id(order.getId());
            oi.setProduct_id(entry.getKey().getId());
            oi.setBuynum(entry.getValue());
            list.add(oi);
        }
            order.setMoney(money);
            orderService.addOrder(order, list);
            cart.clear();
            return "redirect:orderList";
        }

    @RequestMapping("orderList")
    public String orderList(Model model,HttpSession session){
        Object obj = session.getAttribute("user_session");
        String uid = ((User)obj).getId();
        //创建业务层对象
        List<OrderInfo> list = orderService.findAllOrderByUid(uid);
        //将结果保存到request作用域中
       model.addAttribute("list", list);
        return "orderList" ;
    }

    @RequestMapping("deleteOrder")
    public String deleteOrder(String id){
        orderService.deleteOrder(id) ;
        return "redirect:orderList" ;
    }

    @RequestMapping("pay")
    public String pay(){
        return "pay" ;
    }

    @RequestMapping("payOrder")
    public String payOrder(String orderid,Model model,String pd_FrpId){
        String p0_Cmd = "Buy";
        String p1_MerId = "10001126856";
        String p2_Order = orderid;
        String p3_Amt = orderService.findOrderById(p2_Order).getMoney() + "";
        p3_Amt = "0.1";//0.1
        String p4_Cur = "CNY";
        String p5_Pid = "";
        String p6_Pcat ="";
        String p7_Pdesc = "";
        String p8_Url = "http://www.easymall.com/Callback.action";
        String p9_SAF = "";//送货地址
        String pa_MP = "";
        String pr_NeedResponse ="1";
        String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid,
                p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl");
        model.addAttribute("p0_Cmd",p0_Cmd);
        model.addAttribute("p1_MerId",p1_MerId);
        model.addAttribute("p2_Order",p2_Order);
        model.addAttribute("p3_Amt",p3_Amt);
        model.addAttribute("p4_Cur",p4_Cur);
        model.addAttribute("p5_Pid",p5_Pid);
        model.addAttribute("p6_Pcat",p6_Pcat);
        model.addAttribute("p7_Pdesc",p7_Pdesc);
        model.addAttribute("p8_Url",p8_Url);
        model.addAttribute("p9_SAF",p9_SAF);
        model.addAttribute("pa_MP",pa_MP);
        model.addAttribute("pd_FrpId",pd_FrpId);
        model.addAttribute("pr_NeedResponse",pr_NeedResponse);
        model.addAttribute("hmac",hmac);

        return "confirm" ;
    }

    @RequestMapping("http://www.easymall.com/Callback.action")
    public String Callback(HttpServletResponse response, String hmac, String p1_MerId, String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt, String r4_Cur,
                           String r5_Pid, String r6_Order, String r7_Uid, String r8_MP, String r9_BType){

        String keyValue = "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl";
        //使用keyValue对以上数据进行加密,比较支付公司发回来的hmac
        boolean isVail = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue);
        if(isVail){//数据没有被修改
            //是转发还是重定向回来的
            if("1".equals(r9_BType)){//重定向过来的
                try {
                    response.getWriter().write("付款操作完成，等待第三方支付平台进一步确认信息...");
                } catch (IOException e) {
                    e.printStackTrace();
                }
				orderService.updatePaystate(r6_Order,1);
            }else if("2".equals(r9_BType)){//点对点通讯过来的
                System.out.println("付款成功");
                //修改订单的支付状态
                orderService.updatePaystate(r6_Order,1);
                //恢复支付公司结果接收成功
                try {
                    response.getWriter().write("success");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            System.out.println("数据被篡改！！！");
        }
        return "redirect:orderList" ;
    }


}
